<template>
  <a-tree-select
    v-bind="$attrs"
    :value="fakeValue"
    :tree-data="treeData"
    :max-tag-count="maxTagCount"
    :tree-default-expand-all="true"
    :tree-checkable="multiple == true"
    :tree-expanded-keys="expandedKeys"
    :tree-check-strictly="multiple == true"
    :label-in-value="multiple == true"
    :tree-node-filter-prop="labelField"
    :dropdown-style="{
      maxHeight: '350px'
    }"
    :field-names="{
      children: 'children',
      label: labelField,
      value: valueField
    }"
    @treeExpand="expand"
    @change="onChange"
  />
</template>
<script>
import { buildTree, findAllChildrenKeys, findInTree } from '@/utils/tree'
export default {
  // 继承
  name: 'SSelectTree',
  props: {
    maxTagCount: {
      type: Number,
      default: 3
    },
    multiple: {
      type: Boolean,
      default: false
    },
    code: String,
    url: String,
    labelField: {
      type: String,
      default: 'text'
    },
    valueField: {
      type: String,
      default: 'value'
    },
    expandAll: {
      type: Boolean,
      default: true
    },
    checkChildren: {
      type: Boolean,
      default: true
    },
    keyField: {
      type: String,
      default: 'id'
    },
    parentKeyField: {
      type: String,
      default: 'parentId'
    },
    modelValue: {
      type: String,
      required: false
    }
  },
  emits: ['change', 'update:modelValue'],
  data() {
    return { fakeValue: this.multiple ? [] : null, treeData: [], expandedKeys: [] }
  },
  watch: {
    modelValue: {
      handler: function (val) {
        if (!val) {
          this.fakeValue = this.multiple ? [] : null
        } else {
          if (!this.multiple) {
            this.fakeValue = val
          } else {
            const array = val.split(',')
            this.fakeValue = []
            array.forEach((item) => {
              this.fakeValue.push({ value: item })
            })
          }
        }
      },
      deep: true
    },
    url(val) {
      this.fakeValue = []
      this.treeData = []
      this.loadData()
    },
    code(val) {
      this.fakeValue = []
      this.treeData = []
      this.loadData()
    }
  },
  created() {
    if (!this.modelValue) {
      this.fakeValue = this.multiple ? [] : null
    } else {
      if (!this.multiple) {
        this.fakeValue = this.modelValue
      } else {
        const array = this.modelValue.split(',')
        this.fakeValue = []
        array.forEach((item) => {
          this.fakeValue.push({ value: item })
        })
      }
    }
    this.loadData()
  },
  methods: {
    getLabel() {
      const labels = []
      if (this.fakeValue && this.fakeValue.length > 0) {
        this.fakeValue.forEach((item) => {
          const r = findInTree(this.treeData, this.valueField, item)
          if (r) {
            labels.push(r[this.labelField])
          }
        })
      }
      return labels.toString()
    },
    expand(e) {
      this.expandedKeys = e
    },
    loadData() {
      this.expandedKeys = []
      if (this.url) {
        this.$api.GET(this.url).then((res) => {
          if (res.data) {
            this.treeData = buildTree(res.data, this.parentKeyField, this.keyField)
            if (this.expandAll) {
              res.data.forEach((item) => {
                this.expandedKeys.push(item[this.valueField])
              })
            }
          }
        })
      } else if (this.code) {
        this.$api.GET('/data/tree/item/selectListByGroupId', { groupId: this.code }).then((res) => {
          if (res.data) {
            this.treeData = buildTree(res.data, this.parentKeyField, this.keyField)
            if (this.expandAll) {
              res.data.forEach((item) => {
                this.expandedKeys.push(item[this.valueField])
              })
            }
          }
        })
      }
    },
    refreshData() {
      this.loadData()
    },

    onChange(items, label, extra) {
      const checkedValues = []
      if (items) {
        if (this.multiple) {
          items.forEach((item) => {
            checkedValues.push(item.value)
          })
          if (extra.checked && this.checkChildren) {
            const array = findAllChildrenKeys(this.treeData, this.valueField, extra.triggerValue)
            if (array.length > 0) {
              array.forEach((item) => {
                if (!checkedValues.includes(item)) {
                  checkedValues.push(item)
                }
              })
            }
          }
        } else {
          checkedValues.push(items)
        }
      }
      this.$emit(
        'update:modelValue',
        checkedValues == undefined || checkedValues.length == 0
          ? undefined
          : checkedValues.toString()
      )
      this.$emit(
        'change',
        checkedValues == undefined || checkedValues.length == 0
          ? undefined
          : checkedValues.toString()
      )
    }
  }
}
</script>
<style>
.mytest {
  background-color: red;
  max-height: 200px;
}
</style>
